import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/pay_model/bank_card_list_model.dart';
import 'package:yysk_app/model/pay_model/cashier_info_query_model.dart';
import 'package:yysk_app/model/pay_model/payment_order_pay_confirm_model.dart';
import 'package:yysk_app/model/pay_model/payment_order_pay_model.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_controller.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/result_payment/result_payment_page.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:lottie/lottie.dart';
import 'package:oktoast/oktoast.dart';

class PayOrderController extends GetxController {
  final txt = '立即支付'.obs;

  final payInfo = Rx<CashierInfoQueryModel?>(null); //订单信息
  late RxBool isRead = true.obs;
  final userTel = ''.obs;
  final code = ''.obs;
  final payMethod = ''.obs;
  var payCards = RxList<BankCardListModel>();
  var drarwCount = 0.obs;
  var smsBtnText = '获取验证码'.obs;
  Timer? _timer;
  int _seconds = 0;
  var payNo = ''.obs;
  var smsController = TextEditingController();
  var phoneController = TextEditingController();
  @override
  // ignore: unnecessary_overrides
  void onInit() {
    super.onInit();
    payMethod.value = Get.parameters['payMethod'] ?? Get.arguments['payMethod'];
    getInfoQuery();
    getBankList();
  }

  @override
  // ignore: unnecessary_overrides
  void dispose() {
    super.dispose();
    _timer?.cancel();
    smsController.dispose();
    phoneController.dispose();
  }

  Future changeSelect(int id) async {
    var iterator = payCards.iterator;
    while (iterator.moveNext()) {
      var item = iterator.current;
      if (id == item.id) {
        item.isSelect = true;
        phoneController.text = item.mobile ?? '';
      } else {
        // 默认选中
        item.isSelect = false;
      }
      drarwCount.value++;
    }
  }

  void onValueChanged(val, type) {
    if (type == 'userTel') {
      userTel.value = val;
    }
    if (type == 'code') {
      code.value = val;
    }
  }

  //银行卡列表
  Future getBankList() async {
    await http.netFetch<List<BankCardListModel>>(
      PayUrl.bankCardList,
      method: Method.post,
      params: {'channel': payMethod.value, 'plat': "USER", 'bindType': 'PAY'},
      success: (res) {
        payCards.value = res.data ?? [];
        if (payCards.isNotEmpty) {
          payCards[0].isSelect = true;
          phoneController.text = payCards[0].mobile ?? '';
        }
      },
    );
  }

  //查询收银台信息
  getInfoQuery() async {
    ConfirmPaymentController confirmController = Get.find();
    try {
      await http.netFetch<CashierInfoQueryModel>(
        PayUrl.infoQuery,
        method: Method.post,
        params: {
          "cashierToken": confirmController.cashierToken.value,
          "userToken": confirmController.token.value,
          "uuid": confirmController.uuid.value,
        },
        success: (result) {
          // print(result);
          payInfo.value = result.data;

          return result;
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  pay() {

    if(payNo.value==''){
       showToast('请先获取验证码');
      return;
    }
    if(isRead.value==false){
       showToast('请同意并阅读免责声明');
      return;
    }
    ConfirmPaymentController confirmController = Get.find();
    if(smsController.text==''){
      showToast('验证码为空');
      return;
    }
    http.netFetch<PaymentOrderPayConfirmModel>(
      PayUrl.orderPayConfirm,
      method: Method.post,
      params: {
        'userToken': confirmController.token.value,
        'payMethod': payMethod.value,
        'smsCode': smsController.text,
        "payNo":payNo.value
      },
      success: (result) {
        if (result.code == 200) {
          Get.toNamed(
            '${ResultPaymentPage.path}?buyNow=1&outTradeNo=${result.data?.outTradeNo}',
            arguments: {'buyNow': '1',"outTradeNo":result.data?.outTradeNo},
          );
        }
      },
    );
  }

  toResult() {
    Get.toNamed(ResultPaymentPage.path);
  }

  void getSmsCode() {
    if (_seconds > 0) return;
    // TODO: 请求服务器发送验证码
    _seconds = 60;
    smsBtnText.value = '60s';
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _seconds--;
      if (_seconds <= 0) {
        timer.cancel();
        smsBtnText.value = '获取验证码';
      } else {
        smsBtnText.value = '${_seconds}s';
      }
    });
  }

  Future getbankCardId() async {
    ConfirmPaymentController confirmController = Get.find();
    final RegExp phoneRegExp = RegExp(r'^1[3-9]\d{9}$');
    if (!phoneRegExp.hasMatch(phoneController.text)) {
      showToast('请输入正确的手机号码格式');
      return;
    }
    String bankCardId = '';
    for (var element in payCards) {
      if (element.isSelect == true) {
        bankCardId = '${element.id}';
      }
    }
    await http.netFetch<PaymentOrderPayModel>(
      PayUrl.orderPay,
      method: Method.post,
      params: {
        'userToken': confirmController.token.value,
        'cashierToken': confirmController.cashierToken.value,
        'payMethod': payMethod.value,
        'returnUrl': 'https://111.com/', //暂时不用
        "bankCardId": bankCardId,
      },
      success: (res) {
        if (res.code == 200) {
          payNo.value = res.data?.payNo ?? '';
          getSmsCode();
          showToast('短信发送成功');
        }
      },
    );
  }
}
